package other.xsy.passlys.account;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.context.ScriptRuntimeContext;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEvent;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventRequest;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.Account;
import com.rkhd.platform.sdk.data.model.CustomerName__c;
import com.rkhd.platform.sdk.data.model.CustomerRelevance__c;
import com.rkhd.platform.sdk.data.model.User;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.service.XoqlService;
import other.xsy.passlys.util.HCXObjectService;
import other.xsy.passlys.util.HcUtils;

import javax.xml.transform.Result;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 判断用户创建的NA客户数量是否已达上限
 * @Author 黎炎松
 * 2024-08-28 14:41
 */
public class CheckAddAccountCount implements ApprovalEvent {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "判断用户的NA客户数量是否已达上限 ==> ";

    /**
     * 审批触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public ApprovalEventResponse execute(ApprovalEventRequest request) throws ScriptBusinessException {
        logger.info(LOGGER_MSG + "触发开始");
        logger.info("ObjectApiKey:" + request.getEntityApiKey() + " , DataId:" + request.getDataId());

        ApprovalEventResponse response = new ApprovalEventResponse();
        try {
            Account account = new Account();
            account.setId(request.getDataId());
            account = hcxObjectService.get(account);
            account.setReportingStatus__c(2);
            response = checkAccountCounts(account);
        } catch (ApiEntityServiceException e) {
            response.setSuccess(false);
            response.setMsg("判断用户的NA客户数量是否已达上限异常: " + e.getMessage());
        }
        return response;
    }

    public static void main(String[] args) throws ApiEntityServiceException {
        CheckAddAccountCount checkAddAccountCount = new CheckAddAccountCount();

        Account account = new Account();
        account.setId(3444609970313796L);
        account = hcxObjectService.get(account);
        checkAddAccountCount.checkAccountCounts(account);

        //Account account = new Account();
        //account.setId(3441813153421898L);
        //account.setReportingStatus__c(2);
        //Boolean update = hcxObjectService.update(account);
        //System.out.println("update = " + update);
    }

    /**
     * 检查用户创建NA客户是否已达上限
     * @param account
     * @return
     */
    public ApprovalEventResponse checkAccountCounts(Account account) {
        ApprovalEventResponse response = new ApprovalEventResponse();
        response.setSuccess(true);
        response.setMsg("success");
        try {
            logger.info(LOGGER_MSG + "处理开始");
            // 获取当前客户的数据
            Long accountId = account.getId();
            Long entityType = account.getEntityType();
            Long ownerId = account.getOwnerId();
            Integer kaBody = account.getKaBody__c();
            Integer reportingStatus = account.getReportingStatus__c();


            // 获取当前数据所有人可创建的NA客户数量
            User user = new User();
            user.setId(ownerId);
            user = hcxObjectService.get(user);
            Integer decisionType = user.getDecisionType__c(); // NA客户判定类型 1:母子为1 (查询去重的一级客户主体) 2：母子为2 （查询当前用户创建的客户）
            Long maxQuantity = user.getMaxQuantity__c(); // NA客户上限数量
            logger.info(LOGGER_MSG + "user: "  +user);
            if (decisionType == null || maxQuantity == null) {
                logger.info(LOGGER_MSG + "用户没有进行配置NA客户上限数量，不进行拦截");
                return response;
            }

            // 判断当前创建的客户是否是 NA 客户 3201223101025618
            Long naEntityType = 3201223101025618L;
            if (!Objects.equals(entityType, naEntityType) || (decisionType == 1 && kaBody == null) || (accountId != null && !Arrays.asList(2, 3).contains(reportingStatus))) {
                logger.info(LOGGER_MSG + "类型不是NA客户、客户判断类型为1且客户主体为空、编辑不是报表中、报备通过状态无需处理");
                return response;
            }


            // 查询报备状态报备中、报备通过的数据 NA客户判定类型,排除掉当前  1:母子为1 (查询去重的一级客户主体) 2：母子为2 （查询当前用户创建的客户）  客户主体:kaBody__c
            String sql = String.format("select id,kaBody__c from account where reportingStatus__c in (2,3) and entityType = %s and ownerId = %s", naEntityType, ownerId);
            if (accountId != null) {
                // 新增前的情况不会有客户id
                sql += " and id != " + accountId;
            }
            List<JSONObject> accountList = hcxObjectService.batchXoqlQuery(sql);
            int hasAccountCount = accountList.size();
            if (decisionType == 1) {
                // 去重，判断当前新增的客户主体是否包含在当前
                List<Integer> accountMains = accountList.stream().filter(v -> v.getInteger("kaBody__c") != null).map(v -> v.getInteger("kaBody__c")).distinct().collect(Collectors.toList());
                hasAccountCount = accountMains.size();
                if (accountMains.contains(kaBody)) {
                    logger.info(LOGGER_MSG + "当前客户主体已存在，允许新增");
                    return response;
                }
            }

            logger.error(LOGGER_MSG + "配置数量: " + maxQuantity);
            logger.error(LOGGER_MSG + "存在数量: " + hasAccountCount);
            if (hasAccountCount >= maxQuantity) {
                logger.error(LOGGER_MSG + "已超NA客户上限数量，不允许新增");
                response.setSuccess(false);
                response.setMsg(String.format("当前用户'%s': NA客户数量已超上限 (最大NA客户数量为: %s)", user.getName(), maxQuantity));
                return response;
            }

            logger.error(LOGGER_MSG + "允许新增");
            return response;
        } catch(Exception e) {
            logger.error(LOGGER_MSG + "判断异常: " + e.getMessage());
            response.setSuccess(false);
            response.setMsg("判断异常: " + e.getMessage());
            return response;
        }
    }



}
